<?php 
$settings_file="GP_settings.php";
$secrets_file="GP_secrets.php";
$password_file="GP_password.php";
$minimum_password_length=6;

/* 	Width of a default panel block in pixels
	WARNING: some widths are hardcoded. */
$block_width=600;


define ('WARNING', 0);
define ('ERROR', 1);
define ('OKAY', 2);
define ('INFO', 3);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
	<HEAD>
		<title>GPin Admin Panel</title>
		<meta charset="UTF-8">
		<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
		<META http-equiv="Content-Style-Type" content="text/css">
		<LINK href="GP_style.css" rel="stylesheet" type="text/css">
        <script type="text/javascript" src="GP_scripts.js"></script>
<?php 
	//Load settings from the settings file
	if(file_exists($settings_file))
		require($settings_file);	
	if (isset($settings))
		$settings=unserialize(stripslashes($settings));
	else 
		$settings=default_settings();
	if (isset($_GET['action']) && $_GET['action']=='setmap')
	{
		$settings['map_center']['latitude']=$_POST['lat'];
		$settings['map_center']['longtitude']=$_POST['lng'];
		$settings['map_zoom']=$_POST['zoom'];
		$settings['map_type_id']=$_POST['maptypeid'];
	}
	extract ($settings);
	
	if (isset($api_key) && $api_key!='')
	echo '<script src="https://maps.googleapis.com/maps/api/js?key='.$api_key.'&sensor=false" type="text/javascript"></script>';
	else if (isset($_POST['api_key']))
	echo '<script src="https://maps.googleapis.com/maps/api/js?key='.$_POST['api_key'].'&sensor=false" type="text/javascript"></script>';
	
	$id=$lat=$lng=0;
	$brief=$description='';
	
	if(file_exists($secrets_file))
	{
		if (isset($_GET['id']))
		{
		  db_conn();
		 $id=(int)$_GET['id'];
		 $query=mysql_query("SELECT id, lat, lng, UNIX_TIMESTAMP(date) as date, brief, description FROM pins WHERE id=$id");
		 if ($row=mysql_fetch_assoc($query))
		 {
			$map_center['latitude']=$lat=$row['lat'];
			$map_center['longtitude']=$lng=$row['lng'];
			$map_zoom=$map_zoom+1;
			$brief=$row['brief'];
			$description=$row['description'];
		 }
		}
	}

?>
	</HEAD>
	<BODY onload='<?php
	echo 'initialize("map_canvas",'.$map_zoom.', '.$map_center['latitude'].', '.$map_center['longtitude'].', google.maps.MapTypeId.'.strtoupper($map_type_id).');';
?> '>
<div class="adminpanel">
<?php

$panel=new Panel();

/* Force HTTPS. */
if($_SERVER["HTTPS"] != "on")
 header("Location: https://". $_SERVER["SERVER_NAME"] .($_SERVER["SERVER_PORT"] != "80"?":".$_SERVER["SERVER_PORT"]:"").$_SERVER["REQUEST_URI"]);
/* If the database connection was not configured, prompt for connection settings */
else if(!file_exists($secrets_file))
{
	$db_set=(	isset($_POST['db'])
			&&	isset($_POST['db']['host'])
			&&	isset($_POST['db']['name'])
			&&	isset($_POST['db']['user'])
			&&	isset($_POST['db']['pass']) );
	if (	$db_set
		&& 	db_test(	$_POST['db']['host'], 
						$_POST['db']['name'], 
						$_POST['db']['user'], 
						$_POST['db']['pass']
					)
	)
	{
			$handle=fopen ($secrets_file, "x");
			fwrite($handle,'<?php $db_host = "'.$_POST['db']['host'].'"; $db_name = "'.$_POST['db']['name'].'"; $db_user = "'.$_POST['db']['user'].'"; $db_pass = "'.$_POST['db']['pass'].'"; ?>');
			fclose($handle);
			echo '<script language="javascript">
			alert("Database connection settings verified and written to file.");
			window.location = window.location.href;
			</script>';
	}
	else
	{
		if ($db_set)
			message_block('Invalid connection settings!<br>Settings will NOT be saved!', ERROR);
		else 
			message_block('Database connection not configured!', WARNING);
		if (file_exists($secrets_file))
			require($secrets_file);
		if (!isset($_POST['db']['host']))
			if (isset($db_host))
				$_POST['db']['host']=$db_host;
			else
				$_POST['db']['host']='localhost';
		if (!isset($_POST['db']['name']))
			if (isset($db_name))
				$_POST['db']['name']=$db_name;
			else
				$_POST['db']['name']='';
		if (!isset($_POST['db']['user']))
			if (isset($db_user))
				$_POST['db']['name']=$db_user;
			else
				$_POST['db']['user']='root';		
		echo '<br>';
		$panel->begin("Please input the database connection settings", true, $block_width, 'tools');
		echo '
		<form class="RigidForm" action="?" method="post" autocomplete="off">
				<label>Host:</label><input type="text" name="db[host]" value="'.htmlspecialchars ($_POST['db']['host']).'"/><br/>
				<label>Schema:</label><input type="text" name="db[name]" value="'.htmlspecialchars ($_POST['db']['name']).'"/><br/>
				<label>User:</label><input type="text" name="db[user]" value="'.htmlspecialchars ($_POST['db']['user']).'"/><br/>
				<label>Password:</label><input type="password" name="db[pass]"  value=""/><br/>
				<label></label><input type="submit" value="Go!"/><br/>
		</form>';
		$panel->end();
	}
}
else
/* If the password was not set, prompt for new password */
if (!file_exists($password_file))
{
	if (isset($_POST['password']) && isset($_POST['password_confirm']))
	{
		$password_salt=random_salt();
		if ($_POST['password']!=$_POST['password_confirm'])
			message_block('Entered passwords do not match.', ERROR);
		else if (strlen($_POST['password'])<$minimum_password_length)
			message_block('This password is too short.<BR/>It must be at least '.$minimum_password_length.' characters long.', WARNING);
		else
		{
			$handle=fopen ($password_file, "x");
			fwrite($handle,	'<?php $password_hash = "'.crypt ($_POST['password'], $password_salt).'"; $password_salt = "'.$password_salt.'"; ?>' );
			fclose($handle);
			echo '<script language="javascript">
			alert("Password confirmed and written to file.");
			window.location = window.location.href;
			</script>';
		}
	}
	else if (isset($_POST['password']) || isset($_POST['password_confirm']))
		message_block('Entered passwords do not match.', ERROR);
	else
		message_block('No password set.', WARNING);
	echo '<br>';

	$panel->begin("Set the system password", true, 350, 'tools');
	echo '
	<form class="RigidForm" action="?" method="post">
		<label>Password:</label>
		<input type="password" name="password"  value=""/><br/>
		<label>Confirm:</label>
		<input type="password" name="password_confirm"  value=""/><br/>
		<label></label>
		<input type="submit" value="Go!"/><br/>
	</form>';
	$panel->end();
}
else
/* Allow user to log in */
{	
	$authorized=false;
	if ((isset($_POST['logout']) || isset($_GET['logout'])) && isset($_COOKIE['password']))
	{
		setcookie("password", "", time() - 3600, "/");
		unset($_COOKIE['password']);
		message_block('Logged out.', INFO);
	}
	else
	{
		require($password_file);
		if (isset($_COOKIE['password']) && $_COOKIE['password']==crypt($password_hash,getip()))
				$authorized=true;
		else if (isset($_POST['password']))
		{
			if($password_hash==crypt($_POST['password'], $password_salt))
			{
				/* The cookie is valid for three hours and keyed to the user's IP */
				setcookie("password",crypt($password_hash,getip()), time()+60*60*3, "/");
				$_COOKIE['password']=crypt($password_hash,getip());
				$authorized=true;
			}
			else 
				message_block('Incorrect password.', WARNING);
			unset($_POST['password']);
		}
	}
	if (!$authorized)
	{
		echo '<br>';
		$panel->begin("Enter password to log in", true, 350, 'lock');
		echo '<form class="RigidForm" action="?" method="post">
				<label>Password:</label>
				<input type="password" name="password"  value=""/><br/>
				<label></label>
				<input type="submit" value="Go!"/><br/>
		</form>';
		$panel->end();
	}
	else 
	/* User has logged in.*/
	{
		$pass_err=false;
		if 	(isset($_POST['passchange']))
		{
			if ( isset($_POST['passchange']['new_password']) && isset($_POST['passchange']['confirm_password']) && $_POST['passchange']['new_password'] == $_POST['passchange']['confirm_password'])
			{
				 if ($password_hash==crypt($_POST['passchange']['old_password'], $password_salt))
				{
					if (strlen($_POST['passchange']['new_password'])<$minimum_password_length)
					{
						message_block('Passwords must be at least '.$minimum_password_length.' characters.<br/>
						Password not changed.', ERROR);
						$pass_err=true;
					}
					else
					{
						$password_salt=random_salt();
						$handle=fopen ($password_file, "w");
						fwrite($handle,'<?php $password_hash = "'.crypt ($_POST['passchange']['new_password'], $password_salt).'"; $password_salt = "'.$password_salt.'"; ?>');
						fclose($handle);
						message_block('New password saved to file.', OKAY);
					}
				}
				else
				{
					message_block('Old password does not match.<br/>
					Password not changed.', ERROR);
					$pass_err=true;
				}
			}
			else
			{
				message_block('Entered passwords do not match.', ERROR);
				$pass_err=true;
			}
		}
		if  (isset($_POST['password']) && strlen($_POST['password'])<$minimum_password_length)
		{
			message_block('Passwords should be at least '.$minimum_password_length.' characters.<BR> Change your password.', WARNING);
			$pass_err=true;
		}
		$panel->begin('Password', $pass_err);
		echo 
'			<form class="WideForm" action="?" method="post" autocomplete="off">
				<label>Current Password:</label><input type="password" name="passchange[old_password]"  value=""/><br/>
				<label>New Password:</label><input type="password" name="passchange[new_password]"  value=""/><br/>
				<label>Confirm:</label><input type="password" name="passchange[confirm_password]"  value=""/><br/>
				<label></label><input type="submit" value="Go!"/><br/>
			</form>';
		$panel->end();
	
		$db_set=(	isset($_POST['db'])
				&&	isset($_POST['db']['host'])
				&&	isset($_POST['db']['name'])
				&&	isset($_POST['db']['user'])
				&&	isset($_POST['db']['pass']) );
		if ($db_set)
		{
			if (db_test($_POST['db']['host'], 
						$_POST['db']['name'], 
						$_POST['db']['user'], 
						$_POST['db']['pass'] ) )
			{
				$handle=fopen ($secrets_file, "w");
				fwrite($handle, '<?php $db_host = "'.$_POST['db']['host'].'"; $db_name = "'.$_POST['db']['name'].'"; $db_user = "'.$_POST['db']['user'].'";	$db_pass = "'.$_POST['db']['pass'].'"; ?>');
				fclose($handle);
				message_block("New connection settings have been saved.", OKAY);
			}
			else
				message_block("Invalid connection settings.<br>New settings will not be saved!", ERROR);
		}
		$conn_test=db_test();
		if (!$conn_test)
			message_block("Error connecting to database.<br>Check database status for details.", ERROR);
		else
		{	
			// Silent database validation; 
			// Does not return error messages or consider missing tables to be errors.
			$db_ok=db_validate();
			if(!$db_ok)
		message_block('Invalid table structure.<br>
Check database status for details.</form>', ERROR);
		}
		$panel->begin("Database", !$conn_test || !$db_ok);
	echo '<div class="report" style="width:'.$block_width*(2/3).'px;">
	';
	if (!isset($db_host))
		$db_host='localhost';
	if (!isset($db_user))
		$db_user='root';
	if (!isset($db_name))
		$db_name='';
	if (!isset($db_pass))
		$db_pass=false;
	/* Test database connection. */
		if ($conn_test)
		{
			// Database validation again, this time non-silent.
			// Yes, we checked for that before in the silent mode... it _is_ kind of WTFy.
			db_validate(false);
		}
		else db_test($db_host, $db_name, $db_user, $db_pass, false);
		echo '</div>';

	if (file_exists($secrets_file))
		require($secrets_file);
	

	echo '	
	<form class="WideForm" action="?" method="post" autocomplete="off">
		<label>Host:</label><input type="text" name="db[host]" value="'.htmlspecialchars ($db_host).'"/><br/>
		<label>Schema:</label><input type="text" name="db[name]" value="'.htmlspecialchars ($db_name).'"/><br/>
		<label>User:</label><input type="text" name="db[user]" value="'.htmlspecialchars ($db_user).'"/><br/>
		<label>Password:</label><input type="password" name="db[pass]"  value=""/><br/>
		<label></label><input type="submit" value="Go!"/><br/>
	</form>';
	$panel->end();
	
	if (isset($_POST['api_key']))
	{
		if(strlen($_POST['api_key'])>0)
		{
			$_POST['api_key']=trim($_POST['api_key']);
			if ($api_key!='')
			{
				if ($_POST['api_key']!=$api_key)
					message_block('Google API Key has been changed.', OKAY);
			}
			else
				message_block('Google API Key has been set.', OKAY);
			$settings['api_key']=$api_key=$_POST['api_key'];
			write_settings();
		}
	}
	if($api_key=='')
	{
		message_block('Google API Key not set.', WARNING);
	}
	$panel->begin("API Key", $api_key=='');
			echo
			'		<form class="APIForm" action="?" method="post">
					<label>API Key:</label><input type="text" class="text" name="api_key" value="'.htmlspecialchars($api_key).'"/><input type="submit" class="button" value="Go!"/><br/>
					</form>
			';
	$panel->end();
	
	if ($api_key!='')
	{
		$panel->begin("Manage View / Add and Edit Pins", true);
			?>
			<div id="map_canvas" style="width:595px; height:450px;"></div>
				<div style="display: table; margin-top:5px; margin-bottom:5px; ">
				<div style="display: table-row; width:auto;align:center;">
			<?php
	
				$panel->blank(100);
				echo '<form id="mapView" method="post" action="?action=setmap">
				<input id="mapViewLat" type="hidden" name="lat" value="">
				<input id="mapViewLng" type="hidden" name="lng" value="">
				<input id="mapViewZoom" type="hidden" name="zoom" value="">
				<input id="mapViewType" type="hidden" name="maptypeid" value="">';
				$panel->button('Store view!', 'okay', false, "document.getElementById('mapView').submit();");
				echo'</form>';
				$panel->blank(100);
				
			?>
				</div>
				<div style="display:table-row; width:auto;">
			<?php
				$panel->blank(100);
				
				echo '
				<form id="EventForm" method="post" action="?action=setEvent">
				<div id="EventFormDiv" style="width:auto;'.(isset($_GET['id'])?'':'display:none;').'" class="block warning_block RigidForm" >
				<input id="EventForm_id" type="hidden" name="id" value="'.$id.'">
				<input id="EventForm_lat" type="hidden" name="lat" value="'.$lat.'">
				<input id="EventForm_lng" type="hidden" name="lng" value="'.$lng.'">
				<label>Brief:</label><textarea name="brief" rows="1" cols="22">'.htmlspecialchars($brief).'</textarea><br>
				<label>Description:</label><textarea name="description" rows="4" cols="22">'.htmlspecialchars($description).'</textarea><br>
				<label></label>
				';
				$panel->button((isset($_GET['id'])?'Save':'Add'), 'okay', false, "document.getElementById('EventForm').submit();");
				echo '
				</div>
				</form>
				';
				$panel->blank(100);

			?>
				</div>
				</div>
			<?php

		$panel->end();
			
		if (isset($_GET['action']) && $_GET['action']=='setEvent')
		{
			$lat=$_POST['lat'];
			$lng=$_POST['lng'];
			$brief=$_POST['brief'];
			$description=$_POST['description'];
			mysql_query("INSERT INTO `pins` ( `id`, `date`,`lat`, `lng`, `brief`, `description`) VALUES
(".$_POST['id'].", NOW(), '$lat', '$lng', ".sqlesc($brief).", ".sqlesc($description).") ON DUPLICATE KEY UPDATE lat='$lat', lng='$lng', brief=".sqlesc($brief).", description=".sqlesc($description));
		}
		if (isset($_GET['del']))
		{
			mysql_query("DELETE FROM `pins` WHERE id=".$_GET['del']);
		}
		if (isset($_GET['limit']) && $_GET['limit']>0)
			$limit=$settings['limit']=$_GET['limit'];
		$panel->begin("Pins", false);
						echo '
				<form id="LimitForm" method="get" action="?">
				<div id="EventFormDiv" style="width:500px;" class="block warning_block RigidForm" >
				<label>Display max:</label><input id="EventForm_id" type="text" name="limit" value="'.$limit.'">
				<label></label>
				';
				$panel->button("Set", 'okay', false, "document.getElementById('LimitForm').submit();");
				echo '
				</div>
				</form>
				';
		$roman=array( 	0=>null,
						1=>'I',
						2=>'II',
						3=>'III',
						4=>'IV',
						5=>'V', 
						6=>'VI', 
						7=>'VII', 
						8=>'VIII', 
						9=>'IX', 
						10=>'X', 
						11=>'XI', 
						12=>'XII');
		$query=mysql_query("SELECT id, lat, lng, UNIX_TIMESTAMP(date) as date, brief, description FROM pins ORDER BY id DESC");
		while ($row = mysql_fetch_assoc($query))
		{
				$d=date ('j',$row['date']);
				$m=$roman[date('n', $row['date'])];
				$y=date('Y', $row['date']);
				$h=date('H:i', $row['date']);
				$nicedate="$d $m $y, $h";		  
				$row['brief']=str_replace (array("\n", "\r"), array("<br>"), htmlspecialchars($row['brief']));
				$row['description']=str_replace (array("\n", "\r"), array("<br>"), htmlspecialchars($row['description']));
		
				echo '<div style="width:500px;" class="block warning_block RigidForm">';
				
				echo '<img src="http://maps.googleapis.com/maps/api/staticmap?center='.$row['lat'].','.$row['lng'].'&zoom='.($map_zoom+2).'&format=jpg&size=400x150&key='.$api_key.'&markers='.$row['lat'].','.$row['lng'].'&sensor=true"><br>';
				$rows=array('Date'=>$nicedate, 'Brief'=>$row['brief'],'Description'=>$row['description']);
				
				foreach ($rows as $key=>$val)
				echo '<label>'.$key.'</label><span style="text-align:left; align:left;">'.$val.'</span></br>';
				
				echo '<label>';
				$panel->button("Edit", 'tools2', "?id=".$row['id'], "self.location='?id=".$row['id'].";");
				echo '</label><span>';
				$panel->button("Delete", 'error', "?del=".$row['id'], "self.location='?del=".$row['id'].";");
				echo '</span>';
				echo '</div>';
		}
		$panel->end();
	}
	
	echo 
	'
	<div style="display: table-row; width:auto;">';
	$panel->button('Reload', 'reload', '?');
	$panel->blank($block_width/2);
	$panel->button('Log Out', 'power', '?logout');
	
	echo '
	</div>
	<br/>
	<br/>
	';
	write_settings();
	}
}
?>

</div>
	</BODY>
</HTML>
<?php
function sqlesc($x) 
{
    return "'".mysql_real_escape_string($x)."'";
}
function unesc($x)
{
	if (get_magic_quotes_gpc())
		return stripslashes($x);
	return $x;
}
function db_test($db_host=false, $db_name=false, $db_user=false, $db_pass=false, $silent=true)
{
	if ($silent)
		echo '<div style="display:none;">';
	if ($db_host==false && $db_user==false && $db_pass==false && $db_name==false)
	{
		global $secrets_file;
		if(!file_exists($secrets_file))
		{
			if ($silent)
				echo '</div>';
			return false;
		}
		else
			require($secrets_file);
	}
	if (!mysql_connect($db_host, $db_user, $db_pass))
	{
		if(!$silent)
			switch (mysql_errno())
			{
				case 1040:
				case 2002:
					echo('<span class="alert">Too many connections. Please try again later.</span><br/>'); 
					break;
				default:
					echo('<span class="alert">[' . mysql_errno() . '] dbconn: mysql_connect: ' . mysql_error().'</span>');
					break;
			}
		if ($silent)
			echo '</div>';
		return false;
	}
	if(@mysql_select_db($db_name))
	{
		if ($silent)
			echo '</div>';
		return true;
	}
	else
	{
		if ($silent)
			echo '</div>';
		return false;
	}
}
function db_conn()
{
	global $secrets_file;
	require($secrets_file);
    if (!@mysql_connect($db_host, $db_user, $db_pass))
    {
	  switch (mysql_errno())
	  {
		case 1040:
		case 2002:
			die("Too many connections. Please try again later.");
        default:
    	    die("[" . mysql_errno() . "] dbconn: mysql_connect: " . mysql_error());
      }
    }
    mysql_select_db($db_name) or die('dbconn: mysql_select_db: ' + mysql_error());
} 
function getip()
{
	global $_SERVER;

	if(isset($_SERVER['HTTP_CLIENT_IP']))
		return $_SERVER['HTTP_CLIENT_IP'];

	if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && ($_SERVER['HTTP_X_FORWARDED_FOR'] != ''))
	{
		$forwarded=str_replace(',', '', $_SERVER['HTTP_X_FORWARDED_FOR']);
		$forwarded_array=split(' ',$forwarded);
		foreach($forwarded_array as $value)	if (validip($value)) return $value;
	}
	return $_SERVER['REMOTE_ADDR'];
}
function random_salt()
{
    mt_srand(microtime(true)*100000 + memory_get_usage(true));
    return crypt(uniqid(mt_rand(), true), uniqid(mt_rand(), true));
}
function table_exists($table_name)
{
	if (mysql_num_rows( mysql_query("SHOW TABLES LIKE '".$table_name."'"))!=0)
		return true;
	return false;
}
function check_table($table_name, $structure_template, $silent=true)
{
	if (!$silent) echo '<span style="font-weight:bold">Checking table "'.$table_name.'"... </span>';
	if( mysql_num_rows( mysql_query("SHOW TABLES LIKE '".$table_name."'"))==0)
	{	
		if ($silent) return true;
		else
		{
			echo '<span class="alert">Table does not exist!</span><br/>';
			create_table($table_name, $structure_template);
		}
	}
	$q = mysql_query('DESCRIBE '.$table_name);
	$err=0;
	while($row = mysql_fetch_assoc($q)) 
		if (array_key_exists($row['Field'], $structure_template))
		{
			$columns[$row['Field']]=true;
			if ($row['Type']!=$structure_template[$row['Field']])
			{
				$err++;
				if (!$silent) echo '<br>
				<span class="alert" style="padding-left:20px;">'.$row['Field'].' -> Expected: '.$structure_template[$row['Field']].', Found: '.$row['Type'].'</span>';
			}
		}
	foreach ($structure_template as $key => $val)
		if (!array_key_exists($key, $columns))
		{
			$err++;
			if (!$silent) echo '<br>
					<span class="alert" style="padding-left:20px;">'.$key.' -> column missing</span>';
		}
	if ($err==0)
	{
		if (!$silent) echo '<span style="font-weight:bold">OK!</span><br/>
		';
		return true;
	}
	else 
	{
		if (!$silent) echo '<BR/><span class="alert">DONE! ('.$err.' errors)</span><br/>
		';
		return false;
	}
}
function create_table($name, $structure)
{

	$query="CREATE TABLE IF NOT EXISTS `".$name."` (";
	foreach ($structure as $column => $type)
	{
		$query.="\n`".$column."` ".$type." NOT NULL ";
		if ($column=='id') $query.="AUTO_INCREMENT";
		$query.=",";
	}
	if (array_key_exists('id', $structure)) $query.="\nPRIMARY KEY (`id`)";

	$query.="\n) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;";

	mysql_query($query);
	echo '<span style="font-weight:bold">Table "'.$name.'" recreated from template!</span><br/>';
	
}
function db_validate($silent=true)
{
	$signal=true;
	$db_struct=array(
					'pins'=> array(
									'id' => 'int(11)',
									'lat' => 'double',
									'lng' => 'double',
									'date' => 'datetime',
									'brief' => 'text',
									'description' => 'text'
									)
					);
	foreach ($db_struct as $table => $structure)
	{
		$signal=$signal && check_table($table, $structure, $silent);
	}
	return $signal;
}
function message_block($text, $style=WARNING)
{	
	switch ($style)
	{
		case WARNING:
			$style='warning';
			break;
		case ERROR:
			$style='error';
			break;
		case OKAY:
			$style='okay';
			break;
		case INFO:
			$style='info';
			break;
		default:
			break;
	}
	global $block_width;
	echo '
<div style="width:'.($block_width*0.8).'px;" class="block '.$style.'_block" onclick="clickaway(this);"><ul><li class="'.$style.'">'.$text.'</li></ul></div>
	';
}

class Panel
{
	public function begin($header, $open=false, $width=false, $icon=false)
	{
		if (!$width)
		{
			global $block_width;
			$width=$block_width;
		}
		if ($open)
			$display='block';
		else
			$display='none';
		if (!$icon)
		{
			$onclick='onclick="togglethis(this);"';
			if ($open)
				$icon='collapse_closed';
			else
				$icon='collapse_open';
		}
		else
		{
			$onclick=false;
		}
		echo '
<div class="content_block" style="width:'.$width.'px;" ><div class="collapse header" '.$onclick.'><ul><li class="'.$icon.'"><a>'.$header.'</a></li></ul></div><div style="display: '.$display.';"><div>
';
	}
	public function end()
	{
		echo '
</div></div></div>
';
	}
	public function button($header, $icon=false, $href=false, $onclick=false)
	{
		global $block_width;
		$width=$block_width/3;
		if ($icon===false)
			$icon='okay';
		if ($href)
			$href='href="'.$href.'"';
		if ($onclick)
			$onclick="onclick=\"".$onclick."\"";
		echo '
	<div class="content_block" '.$onclick.' style="display: table-cell; width:'.$width.'px;" ><div class="header"><ul><li class="'.$icon.'"><a '.$href.'>'.$header.'</a></li></ul></div></div>
		';
	}
	public function blank($width='auto')
	{
		echo '
		<div style="display: table-cell; width:'.$width.'px;"></div>
		';
	}
}

// Settings: writing to file
function write_settings()
{
	global $settings;
	global $settings_file;	
	$handle=fopen ($settings_file, "w");
	fwrite($handle, "<?php\n\t\$settings=\"".addslashes(serialize($settings))."\";\n?>");
    fclose($handle);
}
// Settings: generating default settings
function default_settings()
{
	$settings['api_key']='';
	$settings['map_center']['latitude']=51.85;
	$settings['map_center']['longtitude']=19.25;
	$settings['map_zoom']=5;
	$settings['map_type_id']="roadmap";
	$settings['limit']=100;
	return $settings;
}
?>